{% extends "base.html" %}

{% block title %}视频通道管理 - 告警系统{% endblock %}

{% block content %}
<div class="container py-4">
    <!-- 页面标题和添加按钮 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="mb-1"><i class="bi bi-camera-video me-2"></i>视频通道管理</h2>
            <p class="text-muted mb-0">管理您的视频通道配置，添加、编辑或删除通道</p>
        </div>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addChannelModal">
            <i class="bi bi-plus-circle me-1"></i> 添加新通道
        </button>
    </div>

    <!-- 错误和成功消息 -->
    {% if error or request.query_params.get('error') %}
    <div class="alert alert-danger alert-dismissible fade show mb-4">
        <i class="bi bi-exclamation-circle me-2"></i> {{ error or request.query_params.get('error')|urldecode }}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    {% endif %}
    
    {% if success or request.query_params.get('success') %}
    <div class="alert alert-success alert-dismissible fade show mb-4">
        <i class="bi bi-check-circle me-2"></i> {{ success or request.query_params.get('success')|urldecode }}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    {% endif %}

    <!-- 搜索和过滤 -->
    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <form id="searchForm" class="row g-3" method="get">
                <div class="col-md-8">
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-search"></i></span>
                        <input type="text" class="form-control" placeholder="搜索通道名称、描述或设备IP" 
                               name="search" value="{{ search or '' }}">
                    </div>
                </div>
                <div class="col-md-4 d-flex gap-2">
                    <button type="submit" class="btn btn-primary flex-grow-1">
                        <i class="bi bi-search me-1"></i> 搜索
                    </button>
                    <button type="button" id="resetSearch" class="btn btn-outline-secondary">
                        <i class="bi bi-arrow-repeat"></i>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 通道列表表格 -->
    <div class="card shadow-sm">
        <div class="card-header bg-white d-flex justify-content-between align-items-center py-3">
            <h5 class="mb-0"><i class="bi bi-list-ul me-2"></i>通道列表</h5>
            <div>
                <!-- <button class="btn btn-sm btn-outline-secondary me-2" id="toggleDebug">
                    <i class="bi bi-bug"></i> 调试模式
                </button> -->
                <span class="badge bg-primary rounded-pill">{{ passages|length }} 个通道</span>
            </div>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>序号</th>
                            <th>通道名称</th>
                            <th>视频流地址</th>
                            <th>设备IP</th>
                            <th>描述</th>
                            <th>区域</th> 
                            <th>状态</th>
                            <th>操作</th>
                            <th>预览</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% if passages|length == 0 %}
                        <tr>
                            <td colspan="9" class="text-center py-5">
                                <div class="py-4">
                                    <i class="bi bi-camera-video-off fs-1 text-muted"></i>
                                    <h5 class="mt-3">未找到视频通道</h5>
                                    <p class="text-muted">请添加新通道或修改搜索条件</p>
                                </div>
                            </td>
                        </tr>
                        {% else %}
                            {% for passage in passages %}
                            <tr>
                                <td class="fw-bold">{{ loop.index }}</td>
                                <td>{{ passage.MediaName }}</td>
                                <td>
                                    <div class="text-truncate" style="max-width: 300px;" 
                                        title="rtsp://{{ passage.MediaUser }}:{{ passage.MediaPassword }}@{{ passage.MediaIp }}:{{ passage.MediaPort }}/Streaming/Channels/{{ passage.MediaNum }}01">
                                        rtsp://{{ passage.MediaUser }}:{{ passage.MediaPassword }}@{{ passage.MediaIp }}:{{ passage.MediaPort }}/Streaming/Channels/{{ passage.MediaNum }}01
                                    </div>
                                </td>
                                <td>{{ passage.BoardIp }}</td>
                                <td>
                                    <div class="text-truncate" style="max-width: 150px;" 
                                        title="{{ passage.MediaDesc }}">
                                        {{ passage.MediaDesc or '-' }}
                                    </div>
                                </td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="text-truncate" style="max-width: 100px;" 
                                            title="{{ passage.AreaName or '未设置区域' }}">
                                            {{ passage.AreaName or '-' }}
                                        </div>
                                        <button class="btn btn-sm btn-link p-0 ms-2 edit-area-btn"
                                                data-id="{{ passage.PassageId }}"
                                                data-current-area="{{ passage.AreaId }}"
                                                title="编辑区域">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                    </div>
                                </td>
                                <td>
                                    <span class="status-badge {% if passage.MediaStatus == '正常' %}status-active{% else %}status-inactive{% endif %}">
                                        {{ passage.MediaStatus }}
                                    </span>
                                </td>
                                <td>
                                    <div class="d-flex gap-2 action-buttons">
                                        <button class="btn btn-sm btn-outline-primary edit-btn" 
                                                data-id="{{ passage.PassageId }}"
                                                data-name="{{ passage.MediaName }}"
                                                data-desc="{{ passage.MediaDesc }}"
                                                data-ip="{{ passage.MediaIp }}"
                                                data-port="{{ passage.MediaPort }}"
                                                data-user="{{ passage.MediaUser }}"
                                                data-password="{{ passage.MediaPassword }}"
                                                data-num="{{ passage.MediaNum }}"
                                                data-board="{{ passage.BoardId }}"
                                                data-area="{{ passage.AreaId }}">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger delete-btn" 
                                                data-id="{{ passage.PassageId }}"
                                                data-name="{{ passage.MediaName }}">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-outline-success preview-btn" 
                                            data-ip="{{ passage.MediaIp }}"
                                            data-port="{{ passage.MediaPort }}"
                                            data-user="{{ passage.MediaUser }}"
                                            data-password="{{ passage.MediaPassword }}"
                                            data-num="{{ passage.MediaNum }}"
                                            data-name="{{ passage.MediaName }}"
                                            data-desc="{{ passage.MediaDesc }}"
                                            data-status="{% if passage.MediaStatus == '正常' %}1{% else %}0{% endif %}">
                                        <i class="bi bi-play-circle"></i> 预览
                                    </button>
                                </td>
                            </tr>
                            {% endfor %}
                        {% endif %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 添加/编辑通道模态框 -->
<div class="modal fade" id="addChannelModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="modalTitle"><i class="bi bi-plus-circle me-2"></i>添加新通道</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="channelForm" method="post">
                <div class="modal-body">
                    <input type="hidden" id="passageId" name="passage_id" value="">
                    <input type="hidden" id="areaId" name="AreaId" value="0">
                        
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">通道名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="mediaName" name="MediaName" required>
                            <small class="text-muted">通道的唯一标识符，不可修改</small>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">通道描述 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="mediaDesc" name="MediaDesc" required>
                            <small class="text-muted">简要描述该通道的用途</small>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">NVR IP地址 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="mediaIp" name="MediaIp" required placeholder="192.168.10.200">
                            <small class="text-muted">NVR设备的IP地址</small>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">NVR端口 <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="mediaPort" name="MediaPort" required value="554">
                            <small class="text-muted">RTSP服务端口，默认554</small>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">用户名 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="mediaUser" name="MediaUser" required placeholder="admin">
                            <small class="text-muted">NVR登录用户名</small>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">密码 <span class="text-danger">*</span></label>
                            <input type="password" class="form-control" id="mediaPassword" name="MediaPassword" required>
                            <small class="text-muted">NVR登录密码</small>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">通道号 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="mediaNum" name="MediaNum">
                            <small class="text-muted">NVR中的通道编号</small>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">设备 <span class="text-danger">*</span></label>
                            <select class="form-select" id="boardId" name="BoardId" required>
                                <option value="">-- 选择设备 --</option>
                                {% for device in devices %}
                                    <option value="{{ device.BoardId }}">{{ device.BoardIp }}</option>
                                {% endfor %}
                            </select>
                            <small class="text-muted">选择通道所属的设备</small>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">区域</label>
                        <select class="form-select" id="areaSelect" name="AreaId">
                            <option value="0">-- 选择区域 --</option>
                            {% for area in areas %}
                                <option value="{{ area.AreaId }}">{{ area.AreaName }}</option>
                            {% endfor %}
                        </select>
                        <small class="text-muted">选择通道所属的区域</small>
                    </div>

                    <div class="alert alert-info">
                        <small>
                            <i class="bi bi-info-circle"></i> RTSP URL将自动生成: 
                            <span id="generatedUrl">rtsp://username:password@ip:port/Streaming/Channels/channel01</span>
                        </small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存配置</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑区域模态框 -->
<div class="modal fade" id="editAreaModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="bi bi-pencil me-2"></i>编辑区域</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="editAreaForm" method="post">
                <div class="modal-body">
                    <input type="hidden" id="editAreaPassageId" name="passage_id">
                    <div class="mb-3">
                        <label class="form-label">选择区域 <span class="text-danger">*</span></label>
                        <select class="form-select" id="editAreaId" name="area_id" required>
                            <option value="">-- 选择区域 --</option>
                            {% for area in areas %}
                                <option value="{{ area.AreaId }}">{{ area.AreaName }}</option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 视频预览模态框 -->
<div class="modal fade" id="videoPreviewModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <div>
                    <h5 class="modal-title" id="videoModalLabel">视频预览</h5>
                    <p class="mb-0 small" id="videoModalDesc"></p>
                </div>
                <div class="d-flex gap-2 align-items-center">
                    <span class="connection-status status-disconnected" id="connectionStatus">未连接</span>
                    <button type="button" class="btn btn-sm btn-light" id="screenshotBtn">
                        <i class="bi bi-camera"></i> 截图
                    </button>
                    <button type="button" class="btn btn-sm btn-light" id="fullscreenBtn">
                        <i class="bi bi-fullscreen"></i> 全屏
                    </button>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
            </div>
            <div class="modal-body p-0">
                <div class="video-container">
                    <video id="previewVideo" autoplay playsinline muted></video>
                    <div class="video-controls">
                        <button class="btn btn-sm btn-primary" id="playBtn"><i class="bi bi-play-fill"></i></button>
                        <button class="btn btn-sm btn-primary" id="pauseBtn"><i class="bi bi-pause-fill"></i></button>
                        <button class="btn btn-sm btn-primary" id="volumeMuteBtn"><i class="bi bi-volume-mute-fill"></i></button>
                        <button class="btn btn-sm btn-primary" id="volumeUpBtn"><i class="bi bi-volume-up-fill"></i></button>
                    </div>
                    <canvas id="screenshotCanvas" style="display:none;"></canvas>
                    <div class="debug-panel" id="debugPanel"></div>
                </div>
            </div>
            <div class="modal-footer">
                <div class="w-100">
                    <div class="progress" style="height: 5px;">
                        <div class="progress-bar" id="connectionProgress" role="progressbar" style="width: 0%"></div>
                    </div>
                    <small class="text-muted" id="connectionInfo">准备连接...</small>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 响应模态框 -->
<div class="modal fade" id="responseModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title"><i class="bi bi-check-circle me-2"></i>操作成功</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>通道配置已成功保存！</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-success" data-bs-dismiss="modal">确定</button>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<style>
    .status-badge {
        padding: 5px 12px;
        border-radius: 20px;
        font-weight: 500;
    }
    
    .status-active {
        background-color: rgba(21, 220, 217, 0.1);
        color: #15dcd9f9;
    }
    
    .status-inactive {
        background-color: rgba(220, 53, 69, 0.1);
        color: #dc3545;
    }
    
    .action-buttons .btn {
        border-radius: 20px;
        padding: 5px 12px;
        font-size: 0.85rem;
    }
    
    /* 视频容器样式 */
    .video-container {
        position: relative;
        padding-bottom: 56.25%; /* 16:9 */
        height: 0;
        overflow: hidden;
        background-color: #000;
    }
    
    .video-container video {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    /* 全屏样式 */
    .video-container.fullscreen {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 9999;
        padding-bottom: 0;
        height: 100vh;
        background-color: black;
    }
    
    .video-container.fullscreen video {
        object-fit: contain;
    }
    
    /* 编辑区域按钮样式 */
    .edit-area-btn {
        color: #6c757d;
        transition: color 0.2s;
    }
    
    .edit-area-btn:hover {
        color: #0d6efd;
    }
    
    .connection-status {
        position: absolute;
        top: 10px;
        right: 10px;
        z-index: 1000;
        padding: 5px 10px;
        border-radius: 4px;
        font-size: 12px;
        font-weight: bold;
    }
    
    .status-connecting {
        background-color: #ffc107;
        color: #000;
    }
    
    .status-connected {
        background-color: #28a745;
        color: #fff;
    }
    
    .status-error {
        background-color: #dc3545;
        color: #fff;
    }
    
    .status-disconnected {
        background-color: #6c757d;
        color: #fff;
    }
    
    .video-controls {
        position: absolute;
        bottom: 10px;
        left: 0;
        right: 0;
        display: flex;
        justify-content: center;
        gap: 10px;
        z-index: 1000;
        opacity: 0;
        transition: opacity 0.3s;
    }
    
    .video-container:hover .video-controls {
        opacity: 1;
    }
    
    .debug-panel {
        position: absolute;
        bottom: 50px;
        left: 10px;
        background: rgba(0, 0, 0, 0.7);
        color: white;
        padding: 10px;
        border-radius: 5px;
        font-size: 12px;
        max-width: 80%;
        max-height: 200px;
        overflow-y: auto;
        display: none;
        z-index: 1000;
    }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    let debugMode = false;
    
    // 更新生成的RTSP URL
    function updateGeneratedUrl() {
        const ip = document.getElementById('mediaIp').value || 'ip';
        const port = document.getElementById('mediaPort').value || 'port';
        const user = document.getElementById('mediaUser').value || 'username';
        const password = document.getElementById('mediaPassword').value || 'password';
        const num = document.getElementById('mediaNum').value || 'channel';
        
        const url = `rtsp://${user}:${password}@${ip}:${port}/Streaming/Channels/${num}01`;
        document.getElementById('generatedUrl').textContent = url;
    }

    // 监听输入框变化
    ['mediaIp', 'mediaPort', 'mediaUser', 'mediaPassword', 'mediaNum'].forEach(id => {
        document.getElementById(id).addEventListener('input', updateGeneratedUrl);
    });

    // 编辑按钮点击事件
    document.querySelectorAll('.edit-btn').forEach(button => {
        button.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            const name = this.getAttribute('data-name');
            const desc = this.getAttribute('data-desc');
            const ip = this.getAttribute('data-ip');
            const port = this.getAttribute('data-port');
            const user = this.getAttribute('data-user');
            const password = this.getAttribute('data-password');
            const num = this.getAttribute('data-num');
            const board = this.getAttribute('data-board');
            const area = this.getAttribute('data-area');

            // 更新模态框标题
            document.getElementById('modalTitle').innerHTML = 
                '<i class="bi bi-pencil me-2"></i>编辑通道: ' + name;
            
            // 填充表单
            document.getElementById('passageId').value = id;
            document.getElementById('mediaName').value = name;
            document.getElementById('mediaDesc').value = desc || '';
            document.getElementById('mediaIp').value = ip || '';
            document.getElementById('mediaPort').value = port || '';
            document.getElementById('mediaUser').value = user || '';
            document.getElementById('mediaPassword').value = password || '';
            document.getElementById('mediaNum').value = num || '';
            document.getElementById('boardId').value = board || '';
            document.getElementById('areaId').value = area || '0';
            document.getElementById('areaSelect').value = area || '0';

            // 设置通道名称为只读（不可修改）
            document.getElementById('mediaName').setAttribute('readonly', true);
            
            // 更新生成的URL
            updateGeneratedUrl();
            
            // 打开模态框
            const modal = new bootstrap.Modal(document.getElementById('addChannelModal'));
            modal.show();
        });
    });
    
    // 编辑区域按钮点击事件
    document.querySelectorAll('.edit-area-btn').forEach(button => {
        button.addEventListener('click', function() {
            const passageId = this.getAttribute('data-id');
            const currentAreaId = this.getAttribute('data-current-area');
            
            // 填充表单
            document.getElementById('editAreaPassageId').value = passageId;
            document.getElementById('editAreaId').value = currentAreaId || '';
            
            // 打开模态框
            const modal = new bootstrap.Modal(document.getElementById('editAreaModal'));
            modal.show();
        });
    });
    
    // 编辑区域表单提交
    document.getElementById('editAreaForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        const passageId = document.getElementById('editAreaPassageId').value;
        
        fetch(`/video-channels/${passageId}/edit-area`, {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(err => {
                    throw new Error(err.detail || '请求失败');
                });
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                // 关闭模态框并刷新页面
                bootstrap.Modal.getInstance(document.getElementById('editAreaModal')).hide();
                window.location.reload();
            } else {
                alert('操作失败: ' + (data.message || '未知错误'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('请求失败: ' + error.message);
        });
    });
    
    // 删除按钮点击事件
    document.querySelectorAll('.delete-btn').forEach(button => {
        button.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            const name = this.getAttribute('data-name');
            
            if (confirm(`确定要删除视频通道 "${name}" 吗？此操作不可恢复！`)) {
                // 发送删除请求
                fetch(`/video-channels/${id}/delete`, {
                    method: 'GET'
                })
                .then(response => {
                    if (response.redirected) {
                        // 重定向到返回的URL
                        window.location.href = response.url;
                    } else {
                        // 处理其他响应
                        return response.text();
                    }
                })
                .then(text => {
                    // 如果返回的是HTML（错误页面），直接替换整个文档
                    document.documentElement.innerHTML = text;
                })
                .catch(error => {
                    console.error('删除请求失败:', error);
                    alert('删除请求失败: ' + error.message);
                });
            }
        });
    });
    
    // 预览按钮点击事件 - 修改为使用参数构建URL
    document.querySelectorAll('.preview-btn').forEach(button => {
        button.addEventListener('click', function() {
            const ip = this.getAttribute('data-ip');
            const port = this.getAttribute('data-port');
            const user = this.getAttribute('data-user');
            const password = this.getAttribute('data-password');
            const num = this.getAttribute('data-num');
            const name = this.getAttribute('data-name');
            const desc = this.getAttribute('data-desc');
            const status = this.getAttribute('data-status');
            
            if (status === '0') {
                alert('该通道当前离线，无法预览');
                return;
            }
            
            // 构建RTSP URL
            const rtspUrl = `rtsp://${user}:${password}@${ip}:${port}/Streaming/Channels/${num}01`;
            logDebug('构建的RTSP URL: ' + rtspUrl);
            
            // 设置模态框标题和描述
            document.getElementById('videoModalLabel').innerText = `视频预览 - ${name}`;
            document.getElementById('videoModalDesc').innerText = desc || '无描述';
            
            // 打开预览模态框
            const modal = new bootstrap.Modal(document.getElementById('videoPreviewModal'));
            modal.show();
            
            // 初始化视频播放
            initVideoPreview(rtspUrl);
        });
    });

    // 重置模态框当关闭时
    document.getElementById('addChannelModal').addEventListener('hidden.bs.modal', function () {
        document.getElementById('modalTitle').innerHTML = '<i class="bi bi-plus-circle me-2"></i>添加新通道';
        document.getElementById('channelForm').reset();
        document.getElementById('passageId').value = '';
        document.getElementById('areaId').value = '0';
        document.getElementById('areaSelect').value = '0';
        
        // 移除只读属性（添加新通道时可编辑）
        document.getElementById('mediaName').removeAttribute('readonly');
        
        // 更新生成的URL
        updateGeneratedUrl();
    });
    
    // 当视频预览模态框关闭时停止视频流
    document.getElementById('videoPreviewModal').addEventListener('hidden.bs.modal', function() {
        stopVideoPreview();
    });
    
    // 表单提交处理
    const form = document.getElementById('channelForm');
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const passageId = document.getElementById('passageId').value;
        const areaId = document.getElementById('areaSelect').value;
        
        // 创建表单数据对象
        const jsonData = {
            MediaName: document.getElementById('mediaName').value,
            MediaDesc: document.getElementById('mediaDesc').value,
            MediaIp: document.getElementById('mediaIp').value,
            MediaPort: parseInt(document.getElementById('mediaPort').value),
            MediaUser: document.getElementById('mediaUser').value,
            MediaPassword: document.getElementById('mediaPassword').value,
            MediaNum: document.getElementById('mediaNum').value,
            BoardId: document.getElementById('boardId').value,
            AreaId: parseInt(areaId),
            passage_id: passageId ? parseInt(passageId) : null
        };
        
        const url = passageId ? `/video-channels/${passageId}/edit` : '/video-channels/add';
        
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(jsonData)
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(err => {
                    throw new Error(err.detail || '请求失败');
                });
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                const responseModal = new bootstrap.Modal(document.getElementById('responseModal'));
                responseModal.show();
                
                // 2秒后刷新页面
                setTimeout(() => {
                    window.location.reload();
                }, 2000);
            } else {
                alert('操作失败: ' + (data.message || '未知错误'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('请求失败: ' + error.message);
        });
    });
    
    // 添加重置搜索功能
    const resetSearchBtn = document.getElementById('resetSearch');
    if (resetSearchBtn) {
        resetSearchBtn.addEventListener('click', function() {
            // 清除搜索输入框的值
            document.querySelector('input[name="search"]').value = '';
            
            // 提交表单（不带搜索参数）
            document.getElementById('searchForm').submit();
        });
    }
    
    // 全屏按钮功能
    document.getElementById('fullscreenBtn').addEventListener('click', function() {
        const videoContainer = document.querySelector('.video-container');
        videoContainer.classList.toggle('fullscreen');
        
        const fullscreenBtn = document.getElementById('fullscreenBtn');
        if (videoContainer.classList.contains('fullscreen')) {
            fullscreenBtn.innerHTML = '<i class="bi bi-fullscreen-exit"></i> 退出全屏';
        } else {
            fullscreenBtn.innerHTML = '<i class="bi bi-fullscreen"></i> 全屏';
        }
    });
    
    // 截图按钮功能
    document.getElementById('screenshotBtn').addEventListener('click', function() {
        const video = document.getElementById('previewVideo');
        const canvas = document.getElementById('screenshotCanvas');
        
        if (!video.srcObject) {
            showError('没有可用的视频流');
            return;
        }
        
        // 设置canvas尺寸与视频相同
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        
        // 绘制视频帧到canvas
        const ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        
        // 将canvas转换为图像并下载
        canvas.toBlob(function(blob) {
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `截图_${new Date().toISOString().replace(/[:.]/g, '-')}.png`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }, 'image/png');
    });
    
    // 视频控制按钮
    document.getElementById('playBtn').addEventListener('click', function() {
        const video = document.getElementById('previewVideo');
        video.play();
    });
    
    document.getElementById('pauseBtn').addEventListener('click', function() {
        const video = document.getElementById('previewVideo');
        video.pause();
    });
    
    document.getElementById('volumeMuteBtn').addEventListener('click', function() {
        const video = document.getElementById('previewVideo');
        video.muted = true;
    });
    
    document.getElementById('volumeUpBtn').addEventListener('click', function() {
        const video = document.getElementById('previewVideo');
        video.muted = false;
    });
    
    // 调试模式切换
    document.getElementById('toggleDebug').addEventListener('click', function() {
        debugMode = !debugMode;
        const debugPanel = document.getElementById('debugPanel');
        debugPanel.style.display = debugMode ? 'block' : 'none';
        this.innerHTML = debugMode ? 
            '<i class="bi bi-bug-fill"></i> 关闭调试' : 
            '<i class="bi bi-bug"></i> 调试模式';
    });

    // 初始化时更新URL
    updateGeneratedUrl();
});

// 显示错误消息
function showError(message) {
    console.error('Error:', message);
    alert('错误: ' + message);
}

// 更新连接状态
function updateConnectionStatus(status, message) {
    const statusElement = document.getElementById('connectionStatus');
    const infoElement = document.getElementById('connectionInfo');
    const progressElement = document.getElementById('connectionProgress');
    
    statusElement.textContent = status;
    infoElement.textContent = message;
    
    // 移除所有状态类
    statusElement.classList.remove('status-connecting', 'status-connected', 'status-error', 'status-disconnected');
    
    // 添加当前状态类
    if (status === '连接中') {
        statusElement.classList.add('status-connecting');
        progressElement.style.width = '30%';
    } else if (status === '已连接') {
        statusElement.classList.add('status-connected');
        progressElement.style.width = '100%';
    } else if (status === '错误') {
        statusElement.classList.add('status-error');
        progressElement.style.width = '0%';
    } else {
        statusElement.classList.add('status-disconnected');
        progressElement.style.width = '0%';
    }
}

// 调试日志
function logDebug(message) {
    console.log('DEBUG:', message);
    if (window.debugMode) {
        const debugPanel = document.getElementById('debugPanel');
        const logEntry = document.createElement('div');
        logEntry.textContent = new Date().toLocaleTimeString() + ': ' + message;
        debugPanel.appendChild(logEntry);
        debugPanel.scrollTop = debugPanel.scrollHeight;
    }
}

// 初始化视频预览
function initVideoPreview(rtspUrl) {
    const videoElement = document.getElementById('previewVideo');
    videoElement.srcObject = null;
    
    updateConnectionStatus('连接中', '正在初始化WebRTC连接...');
    logDebug('初始化视频预览，URL: ' + rtspUrl);
    
    // 创建WebSocket连接
    try {
        const ws = new WebSocket(`ws://${window.location.host}/ws/video`);
        window.videoPreviewWS = ws;
        
        // 创建RTCPeerConnection
        const pc = new RTCPeerConnection({
            iceServers: [
                { urls: 'stun:stun.l.google.com:19302' },
                { urls: 'stun:stun1.l.google.com:19302' }
            ]
        });
        window.videoPreviewPC = pc;
        
        // 处理ICE候选
        pc.onicecandidate = event => {
            if (event.candidate) {
                logDebug('生成ICE候选: ' + event.candidate.candidate);
                ws.send(JSON.stringify({
                    type: 'candidate',
                    candidate: event.candidate
                }));
            }
        };
        
        // 处理远程轨道
        pc.ontrack = event => {
            if (event.streams && event.streams[0]) {
                videoElement.srcObject = event.streams[0];
                updateConnectionStatus('已连接', '视频流已连接');
                logDebug('收到视频流');
            }
        };
        
        // WebSocket消息处理
        ws.onopen = () => {
            updateConnectionStatus('连接中', '正在设置视频流地址...');
            logDebug('WebSocket连接已打开，发送流URL');
            
            // 发送流地址
            ws.send(JSON.stringify({
                type: 'set_stream_url',
                url: rtspUrl
            }));
            
            // 创建offer
            pc.createOffer({
                offerToReceiveVideo: true,
                offerToReceiveAudio: false
            })
            .then(offer => {
                logDebug('创建offer成功');
                return pc.setLocalDescription(offer);
            })
            .then(() => {
                updateConnectionStatus('连接中', '正在发送offer...');
                logDebug('发送offer: ' + JSON.stringify(pc.localDescription));
                ws.send(JSON.stringify({
                    type: 'offer',
                    offer: pc.localDescription
                }));
            })
            .catch(error => {
                console.error('创建offer失败:', error);
                updateConnectionStatus('错误', '创建offer失败: ' + error.message);
                showError('创建视频流失败: ' + error.message);
            });
        };
        
        ws.onmessage = async event => {
            try {
                const message = JSON.parse(event.data);
                logDebug('收到WebSocket消息: ' + event.data);
                
                if (message.type === 'answer') {
                    updateConnectionStatus('连接中', '收到answer，正在设置远程描述...');
                    logDebug('收到answer');
                    await pc.setRemoteDescription(new RTCSessionDescription(message.answer));
                } else if (message.type === 'candidate') {
                    try {
                        logDebug('收到ICE候选');
                        await pc.addIceCandidate(new RTCIceCandidate(message.candidate));
                    } catch (e) {
                        console.error('添加ICE候选失败:', e);
                        logDebug('添加ICE候选失败: ' + e.message);
                    }
                } else if (message.type === 'error') {
                    updateConnectionStatus('错误', message.message);
                    showError('视频流错误: ' + message.message);
                    logDebug('收到错误: ' + message.message);
                } else if (message.type === 'status') {
                    updateConnectionStatus('连接中', message.message);
                    logDebug('状态更新: ' + message.message);
                }
            } catch (error) {
                console.error('处理WebSocket消息失败:', error);
                updateConnectionStatus('错误', '处理消息失败: ' + error.message);
                logDebug('处理消息失败: ' + error.message);
            }
        };
        
        ws.onerror = error => {
            console.error('WebSocket错误:', error);
            updateConnectionStatus('错误', 'WebSocket连接错误');
            showError('视频流连接错误');
            logDebug('WebSocket错误: ' + JSON.stringify(error));
        };
        
        ws.onclose = () => {
            console.log('WebSocket连接关闭');
            updateConnectionStatus('断开', 'WebSocket连接已关闭');
            logDebug('WebSocket连接关闭');
        };
        
    } catch (error) {
        console.error('初始化视频预览失败:', error);
        updateConnectionStatus('错误', '初始化失败: ' + error.message);
        showError('初始化视频预览失败: ' + error.message);
        logDebug('初始化失败: ' + error.message);
    }
}

// 停止视频预览
function stopVideoPreview() {
    if (window.videoPreviewPC) {
        window.videoPreviewPC.close();
        window.videoPreviewPC = null;
        logDebug('关闭RTCPeerConnection');
    }
    if (window.videoPreviewWS) {
        window.videoPreviewWS.close();
        window.videoPreviewWS = null;
        logDebug('关闭WebSocket连接');
    }
    const videoElement = document.getElementById('previewVideo');
    if (videoElement && videoElement.srcObject) {
        videoElement.srcObject.getTracks().forEach(track => track.stop());
        videoElement.srcObject = null;
        logDebug('停止视频轨道');
    }
    
    // 退出全屏
    const videoContainer = document.querySelector('.video-container');
    if (videoContainer.classList.contains('fullscreen')) {
        videoContainer.classList.remove('fullscreen');
        document.getElementById('fullscreenBtn').innerHTML = '<i class="bi bi-fullscreen"></i> 全屏';
        logDebug('退出全屏模式');
    }
    
    updateConnectionStatus('断开', '连接已关闭');
}
</script>
{% endblock %}